import { IDegreeWithHeight } from '@/types/position'
import { computed, ref } from 'vue'
import CesiumBoxSelect from '@/components/common/Cesium/CesiumBoxSelect.vue'
import { ElMessage } from 'element-plus'

type BoxEndCallback = (
    positions: Cesium.Cartesian3[],
    positionLngLat: number[],
) => void

function useBoxSelect(options?: { onBoxEnd?: BoxEndCallback }) {
    // 当前框选的范围
    const currentBoxRange = ref<number[]>([])

    /**
     * @title 现在是否存在框选范围
     */
    const hasBoxRange = computed(
        () => currentBoxRange.value && currentBoxRange.value.length > 1,
    )

    // 当前框选组件实例
    const boxSelectRef = ref<InstanceType<typeof CesiumBoxSelect>>()

    // 当框选结束后执行
    function handleBoxEnd(
        positions: Cesium.Cartesian3[],
        positionLngLat: IDegreeWithHeight[],
    ) {
        console.log('handleBoxEnd positions======>', positions, positionLngLat)

        if (positionLngLat.length < 1) {
            ElMessage.warning('坐标格式不正确')
            return
        }
        const len = positionLngLat.length

        positionLngLat[0]


        currentBoxRange.value = getLtRbPos(positionLngLat)

        // 框选结束后,如果有回调,执行回调
        if (options?.onBoxEnd) {
            options.onBoxEnd(positions, currentBoxRange.value)
        }
    }

    function getLtRbPos(posarr: IDegreeWithHeight[]) {
        const lastIdx = posarr.length - 1

        const lt_lng = Math.min(posarr[0].longitude, posarr[lastIdx].longitude)
        const lt_lat = Math.min(posarr[0].latitude, posarr[lastIdx].latitude)

        const rb_lng = Math.max(posarr[0].longitude, posarr[lastIdx].longitude)
        const rb_lat = Math.max(posarr[0].latitude, posarr[lastIdx].latitude)

        return [lt_lng, lt_lat, rb_lng, rb_lat]
    }

    // 开始框选
    function handleBoxSelect() {
        handleBoxClear()

        boxSelectRef.value?.handleBoxSelect()
    }

    // 清空框选
    function handleBoxClear() {
        currentBoxRange.value = []

        boxSelectRef.value?.handleBoxClear()
    }

    return {
        currentBoxRange,
        boxSelectRef,
        hasBoxRange,
        handleBoxEnd,
        handleBoxSelect,
        handleBoxClear,
        getLtRbPos,
    }
}

export default useBoxSelect
